package com.bjb.vr.common.service;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.ao.ResPlaylistAo;
import com.bjb.vr.common.ao.UmsAccountAo;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.ResPlaycontent;
import com.bjb.vr.common.dto.ResPlaylist;
import com.bjb.vr.common.dto.UmsAccount;
import com.bjb.vr.common.mapper.ResPlaycontentMapper;
import com.bjb.vr.common.mapper.ResPlaylistMapper;
import com.bjb.vr.common.result.BaseResult;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.UmsAccountVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author admin
 * @description 针对表【res_playlist】的数据库操作Service实现
 * @createDate 2022-03-18 18:00:07
 */
@Service
public class ResPlaylistService extends ServiceImpl<ResPlaylistMapper, ResPlaylist> {
    @Autowired
    UmsAccountService umsAccountService;
    @Autowired
    ResPlaycontentService playcontentService;
    @Autowired
    ResPlaylistMapper playlistMapper;
    @Autowired
    ResPlaycontentMapper playcontentMapper;

    @Autowired
    ResLocalResourceService localResourceService;

    @Resource
    FileOperationService fileOperationService;

    /**
     * 根据条件查询课集列表
     *
     * @param resPlaylistAo
     * @param authorization
     * @return
     */
    public BaseResult<ResPlaylistAo> queryPlaylist(ResPlaylistAo resPlaylistAo, String authorization) {
        // 查询用户信息
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        // 分页条件
        Page<ResPlaylist> resPlaylist = new Page<>(resPlaylistAo.getCurrent(), resPlaylistAo.getSize());
        LambdaQueryWrapper<ResPlaylist> queryWrapper = Wrappers.lambdaQuery(ResPlaylist.class);
        // 查询条件
        queryWrapper.eq(ResPlaylist::getAccountId, umsAccountVo.getUserId());
        queryWrapper.like(StringUtils.isNotBlank(resPlaylistAo.getPlayName()), ResPlaylist::getPlayName, resPlaylistAo.getPlayName());
        // 执行查询
        Page<ResPlaylist> playlistPage = playlistMapper.selectPage(resPlaylist, queryWrapper);
        List<ResPlaylist> resPlaylistVos = convertPoToVo(playlistPage.getRecords());
        // 循环遍历出id，插入查询出来的缩略图路径
        for (ResPlaylist playlist : resPlaylistVos) {
            List<String> pathList = playlistMapper.selectPathsById(playlist.getId());
            List<String> newPathList = new ArrayList<>();
            for (String path : pathList) {
                if (StringUtils.isNotBlank(path)) {
                    path = fileOperationService.downloadFile(path);
                    newPathList.add(path);
                }
            }
            String[] paths = newPathList.toArray(new String[newPathList.size()]);
            playlist.setPaths(paths);
        }

        IPage<ResPlaylist> voIPage = new Page<ResPlaylist>(playlistPage.getCurrent(), playlistPage.getSize(), playlistPage.getTotal());
        voIPage.setRecords(resPlaylistVos);
        return CommonResult.Ok().setResult(voIPage);
    }


    /**
     * 新增课集列表
     *
     * @param resPlaylistAo
     * @return boolean
     */
    public boolean addPlaylist(ResPlaylistAo resPlaylistAo) {
        // 查询用户信息
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        //新增逻辑处理
        ResPlaylist playlist = new ResPlaylist();
        playlist.setPlayName(resPlaylistAo.getPlayName());
        playlist.setGmtCreate(LocalDateTime.now());
        playlist.setAccountId(umsAccountVo.getUserId());
        save(playlist);
        String playContentIds = resPlaylistAo.getPlaycontentIds();
        if (!"".equals(playContentIds) && playContentIds != null) {
            String[] idArray = playContentIds.split(",");
            for (int i = 0; i < idArray.length; i++) {
                ResPlaycontent playContent = new ResPlaycontent();
                playContent.setResId(Long.valueOf(idArray[i]));
                playContent.setPlayId(playlist.getId());
                playContent.setPlayOrder(i);
                playContent.setGmtCreate(LocalDateTime.now());
                playContent.setGmtModified(LocalDateTime.now());
                playcontentMapper.insert(playContent);
            }
        }
        return true;
    }


    /**
     * 修改课集列表
     *
     * @param resPlaylistAo
     * @param authorization
     * @return
     */
    public boolean editPlaylist(ResPlaylistAo resPlaylistAo, String authorization) {
        //修改逻辑处理
        ResPlaylist playlist = new ResPlaylist();
        playlist.setId(resPlaylistAo.getId());
        playlist.setPlayName(resPlaylistAo.getPlayName());
        playlist.setGmtModified(LocalDateTime.now());
        return updateById(playlist);
    }

    /**
     * 修改课集列表的课程
     *
     * @param resPlaylistAo
     * @param authorization
     * @return
     */
    public boolean editlistPlayIds(ResPlaylistAo resPlaylistAo, String authorization) {
        // 查询用户信息
        UmsAccountAo umsAccountAo = UmsAccountAo.builder().authorization(authorization).build();
        UmsAccountVo accountInfo = umsAccountService.getAccountInfo(umsAccountAo);
        if (Objects.isNull(accountInfo)) {
            return false;
        }
        //根据playid删除对应的课程内容
        HashMap<String, Object> map = new HashMap<>();
        map.put("play_id", resPlaylistAo.getId());
        playcontentMapper.deleteByMap(map);
        String playContentIds = resPlaylistAo.getPlaycontentIds();
        if (!"".equals(playContentIds) && playContentIds != null) {
            String[] idArray = playContentIds.split(",");
            for (int i = 0; i < idArray.length; i++) {
                ResPlaycontent playContent = new ResPlaycontent();
                playContent.setResId(Long.valueOf(idArray[i]));
                playContent.setPlayId(resPlaylistAo.getId());
                playContent.setPlayOrder(i);
                playContent.setGmtCreate(LocalDateTime.now());
                playContent.setGmtModified(LocalDateTime.now());
                playcontentMapper.insert(playContent);
            }
        }
        return true;
    }


    /**
     * 删除课集列表
     *
     * @param ids
     * @param authorization
     * @return
     */
    public boolean removePlaylist(String ids, String authorization) {
        // 查询用户信息
        UmsAccountAo umsAccountAo = UmsAccountAo.builder().authorization(authorization).build();
        UmsAccountVo accountInfo = umsAccountService.getAccountInfo(umsAccountAo);
        if (Objects.isNull(accountInfo)) {
            return false;
        }
        String[] idArray = ids.split(",");
        Long[] intArray = Convert.toLongArray(idArray);
        //批量删除逻辑
        playlistMapper.deleteBatchIds(Arrays.asList(intArray));
        //批量删除课程集的内容表
        for (String playId : idArray) {
            playcontentService.removePlayContent(Long.valueOf(playId), authorization);
        }
        return true;
    }

    /**
     * 数据类型转换
     *
     * @param resPlaylistlist
     * @return
     */
    private List<ResPlaylist> convertPoToVo(List<ResPlaylist> resPlaylistlist) {
        List<ResPlaylist> resPlaylistAos = new ArrayList<>();
        resPlaylistlist.stream().forEach(resPlaylist -> {
            ResPlaylist resPlaylistAo = new ResPlaylist();
            BeanUtils.copyProperties(resPlaylist, resPlaylistAo);
            resPlaylistAos.add(resPlaylistAo);
        });
        return resPlaylistAos;
    }

    /**
     * 根据用户Id和列表名称查询课程集列表
     *
     * @param accountId
     * @param playName
     * @return
     */
    public boolean queryPlaylistByIdAndName(Long accountId, String playName) {
        Integer count = playlistMapper.selectCount(new LambdaQueryWrapper<ResPlaylist>().eq(ResPlaylist::getPlayName, playName).eq(ResPlaylist::getAccountId, accountId));
        return count > 0 ? true : false;
    }
}




